package com.fwlst.module_home.model

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.fwlst.lib_base.constant.AppConfig
import com.fwlst.lib_base.constant.GlobalUserInfo
import com.fwlst.lib_base.constant.UserRoute
import com.fwlst.lib_base.retrofit.GoodsResponse
import com.fwlst.lib_base.retrofit.PreOrderResponse
import com.fwlst.lib_base.retrofit.JtRetrofitClient
import com.fwlst.module_home.R
import com.fwlst.lib_base.utils.ZfbPaySdk
import com.hjq.toast.Toaster
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

data class PayTypeItem(val id: Int, val name: String, val icon: Int, val selected: Boolean = false)

class MemberViewModel : ViewModel() {
    val TAG = "MemberViewModel"
    var goodsList by mutableStateOf(listOf<GoodsResponse.GoodsItem>())
    var selectedGoods by mutableStateOf<GoodsResponse.GoodsItem?>(null)
    var payTypes by mutableStateOf(listOf<PayTypeItem>())
    private var selectedPayType by mutableStateOf<PayTypeItem?>(null)
    var confirmSelected by mutableStateOf(false)
    var showPayConfirm by mutableStateOf(false)
    var isAutoCheckout by mutableStateOf(false)
    var isLoading by mutableStateOf(false)

    var isWebViewError by mutableStateOf(false)

    var isCreateOrder by mutableStateOf(false)

    private val _isLogIn = MutableStateFlow(false)
    val isLogIn: StateFlow<Boolean> get() = _isLogIn


    init {
        loadDefaultPayTypes()
        fetchGoods()
        // 初始化加载本地用户信息
        _isLogIn.value = GlobalUserInfo.userInfo.value?.token.isNullOrBlank().not()

        viewModelScope.launch {
            GlobalUserInfo.userInfo.collect { user ->
                _isLogIn.value = user != null && user.token.isNotBlank()
            }
        }
    }

    private fun loadDefaultPayTypes() {
        val newPayTypes = mutableListOf<PayTypeItem>()

        if (AppConfig.WXSWITCH) {
            val wxPayType = PayTypeItem(2, "微信支付", R.drawable.home_member_wx_pay, selected = true)
            selectedPayType = wxPayType
            newPayTypes.add(wxPayType)
        }

        if (AppConfig.ZFBSWITCH) {
            // 如果微信没开，支付宝默认选中
            val isSelected = !AppConfig.WXSWITCH
            val zfbPayType = PayTypeItem(4, "支付宝支付", R.drawable.home_member_zfb_pay, isSelected)
            if (isSelected) {
                selectedPayType = zfbPayType
            }
            newPayTypes.add(zfbPayType)
        }

        if (newPayTypes.isEmpty()) {
            Toaster.show("当前无可用支付方式")
        } else {
            payTypes = newPayTypes
        }
    }


    fun selectPayType(payType: PayTypeItem) {
        payTypes = payTypes.map {
            it.copy(selected = it.id == payType.id)
        }
        selectedPayType = payType
    }


    // 获取配置信息
    private fun fetchGoods() {
        viewModelScope.launch {
            try {
                val response = JtRetrofitClient.apiService.getGoods()
                if (response.code == 10000) {
                    goodsList = response.data
                    selectedGoods = response.data.firstOrNull()
                    Log.d(TAG, "商品信息获取成功")
                } else {
                    Log.d(TAG, "商品信息获取失败")
                }
            } catch (e: Exception) {
                Log.d(TAG, "请求失败：${e.message ?: "未知错误"}")
            }
        }
    }

    // 支付预下单
    fun preOrder(context: Context) {
        viewModelScope.launch {
            if (AppConfig.APP_MARKETS == 1 && !confirmSelected) {
                showPayConfirm = true
                return@launch
            }

            if (selectedGoods == null) {
                Toaster.show("请选择商品")
                return@launch
            }

            if (selectedPayType == null) {
                Toaster.show("请选择支付方式")
                return@launch
            }

            if (!isLogIn.value) {
                isAutoCheckout = true
                ARouter.getInstance().build("/base/route/UserActivity")
                    .withString("pageName", UserRoute.USER_LOGIN).navigation()
                return@launch
            }
            isLoading = true
            try {
                val response = JtRetrofitClient.apiService.preOrder(
                    payChannel = selectedPayType?.id.toString(),
                    goodsId = selectedGoods?.id.toString()
                )
                if (response.code == 10000) {
                    Log.d(
                        TAG,
                        "下单成功: 订单号：${response.data.order_no}, order_string： ${response.data.order_string}, Referer：${response.data.Referer}"
                    )
                    handlePay(context, response.data)
                } else {
                    Log.d(TAG, "下单失败，${response.msg}")
                    isLoading = false
                }

            } catch (e: Exception) {
                Log.d(TAG, "请求失败：${e.message ?: "未知错误"}")
                isLoading = false
            }

        }
    }

    private fun handlePay(context: Context, orderInfo: PreOrderResponse.OrderInfo) {
        isCreateOrder = true
        when (selectedPayType?.id) {
            2 -> {
                // 微信支付
                if (isWeChatInstalled(context)) {
                    // 微信H5支付
                    wxH5Pay(context, orderInfo)
                } else {
                    // 提示用户未安装微信
                    Toaster.show("请先安装微信客户端！")
                }

            }

            4 -> {
                //支付宝app
                if (!hadInstalledAliPay(context)) {
                    Toaster.show("请先安装支付宝客户端！")
                    return
                }
                ZfbPaySdk.pay(context, orderInfo.order_string) {}
                isLoading = false
            }

            else -> {
                Toaster.show("暂不支持该支付方式")
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun wxH5Pay(context: Context, orderInfo: PreOrderResponse.OrderInfo) {
        val url = orderInfo.order_string
        val referer = orderInfo.Referer

        if (url.isEmpty() || referer.isEmpty()) {
            Toaster.show("预下单异常，订单信息异常")
            return
        }
        val webView = WebView(context).apply {
            settings.javaScriptEnabled = true
            settings.javaScriptCanOpenWindowsAutomatically = true
            settings.domStorageEnabled = true
            webViewClient = object : WebViewClient() {
                @Deprecated("Deprecated in Java")
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    if (url?.contains("https://wx.tenpay.com") == true) {
                        val extraHeaders = mapOf("Referer" to referer)
                        view?.loadUrl(url, extraHeaders)
                        return true
                    } else {
                        try {
                            if (url!!.startsWith("weixin://")) {
                                context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                                return true
                            }
                        } catch (e: Exception) {
                            Toaster.show("无法拉起微信支付")
                            Log.e(TAG, "无法拉起微信支付: $e")
                            return false
                        }
                    }
                    return true
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    if (isWebViewError) {
                        isWebViewError = false
                        Toaster.show("调取失败，请检查是否安装微信客户端")
                        isLoading = false
                    }
                }

                override fun onReceivedError(
                    view: WebView?,
                    request: WebResourceRequest?,
                    error: WebResourceError?
                ) {
                    super.onReceivedError(view, request, error)
                    isWebViewError = true
                }
            }
        }

        // 加载支付链接，并带上 Referer 请求头
        val extraHeaders = mapOf("Referer" to referer)
        webView.loadUrl(url, extraHeaders)
    }

    //判断是否安装支付宝
    private fun hadInstalledAliPay(context: Context): Boolean {
        val uri = Uri.parse("alipays://platformapi/startApp")
        val intent = Intent(Intent.ACTION_VIEW, uri)
        val componentName = intent.resolveActivity(context.packageManager)
        return componentName != null
    }

    // 判断是否安装微信
    private fun isWeChatInstalled(context: Context): Boolean {
        val packageManager = context.packageManager
        return try {
            val packageInfo = packageManager.getPackageInfo("com.tencent.mm", 0)
            packageInfo.versionName
            true
        } catch (e: Exception) {
            false
        }
    }

    fun updateUserInfo(){
        if (isCreateOrder && selectedPayType?.id ==  2){
            isCreateOrder = false
            isLoading = true
            val oldDays = if (GlobalUserInfo.userInfo.value?.vip_info?.days == null) {
                0
            } else {
                GlobalUserInfo.userInfo.value?.vip_info?.days!!
            }
            GlobalUserInfo.updateUserInfo()
            val newDays = if (GlobalUserInfo.userInfo.value?.vip_info?.days == null) {
                0
            } else {
                GlobalUserInfo.userInfo.value?.vip_info?.days!!
            }

            if (newDays > oldDays){
                Toaster.show("支付成功")
            }else{
                Toaster.show("支付失败, 支付到账可能有延迟，请稍后从个人信息查看最新信息，如有疑问请联系客服处理")
            }
            isLoading = false
        }

    }

}